const { exec } = require("../db/mysql")

const getList = (author, keyword) => {
  let sql = "select * from blogs where 1=1"
  if (author) {
    sql+=`and author=%${author}%`
  }
  if (keyword) {
    sql += `and title=%${title}%`
  }
  return exec(sql)
}

const getDetail = (id='') => {
  let sql = "select * from blogs where 1=1"
  sql += ` and id = ${id}`
  return exec(sql).then((rows) => {
    return rows.length > 0 ? rows[0] : {}
  })
}

const newBlog = (blogData = {}) => {
  let { title, content, createtime, author } = blogData
  let sql = `INSERT INTO blogs(title, content, createtime, author) VALUES('${title}', '${content}', '${createtime}', '${author}')`
  console.log(sql)
  return exec(sql).then((res) => {
    return res
  })
}
const updateBlog = (id, blogData = {}) => {
  if (!id) {
    return ''
  }
  let { title, content, createtime, author } = blogData
  let sql = `update blogs set title='${title}', content='${content}', createtime='${createtime}', author='${author}' where id=${id}`
  return exec(sql).then((res) => {
    return res
  })
}
const delBlog = (id) => {
  if (!id) {
    return ''
  }
  let sql = `DELETE from blogs where id=${id}`
  return exec(sql).then((res) => {
    console.log('res', res)
    return res
  })
}
module.exports = {
  getList,
  getDetail,
  newBlog,
  updateBlog,
  delBlog
}